package com.hanhanxiaochong.zhongxiangchuanmei.view.shop.act;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.hanhanxiaochong.zhongxiangchuanmei.R;
import com.hanhanxiaochong.zhongxiangchuanmei.alipay.Alipay;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.AddressItemBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.HomeDeliverBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.PayDetailBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.PayDetailShoppingBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.PriceBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.WXPayBean;
import com.hanhanxiaochong.zhongxiangchuanmei.presenter.PayDetailPresenter;
import com.hanhanxiaochong.zhongxiangchuanmei.util.FullyLinearLayoutManager;
import com.hanhanxiaochong.zhongxiangchuanmei.util.MessageEvent;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ResourcesUtils;
import com.hanhanxiaochong.zhongxiangchuanmei.util.SharedPreferencesUtil;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ToastUtils;
import com.hanhanxiaochong.zhongxiangchuanmei.util.glide.GlideImgManager;
import com.hanhanxiaochong.zhongxiangchuanmei.view.base.BaseActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.home.act.AppointmentSuccessActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.iview.IPayDetailView;
import com.hanhanxiaochong.zhongxiangchuanmei.view.my.CouponActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.my.act.AddressActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.shop.adapter.PayDetailAdapter;
import com.hanhanxiaochong.zhongxiangchuanmei.widget.ShoppingcartAmountView;
import com.hanhanxiaochong.zhongxiangchuanmei.widget.checkbox.SmoothCheckBox;
import com.hanhanxiaochong.zhongxiangchuanmei.wxapi.WXPayUtils;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.RetrofitSource;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

/**
 * Author : 贾桐
 * E-mail : 653773284@qq.com
 * Time   : 2018/5/2.
 * Desc   :
 */

public class PayDetailActivity extends BaseActivity<PayDetailPresenter> implements IPayDetailView, AMapLocationListener {
    @BindView(R.id.img_left)
    ImageView imgLeft;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.cb_alipay)
    SmoothCheckBox cbAlipay;
    @BindView(R.id.cb_wechat)
    SmoothCheckBox cbWechat;
    @BindView(R.id.cb_bank)
    SmoothCheckBox cbBank;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.cb_home)
    SmoothCheckBox cbHome;
    @BindView(R.id.ll_home)
    LinearLayout llHome;
    @BindView(R.id.txt_address)
    TextView txtAddress;
    @BindView(R.id.cb_express)
    SmoothCheckBox cbExpress;
    @BindView(R.id.ll_express)
    LinearLayout llExpress;
    @BindView(R.id.tv_address_name)
    TextView tvAddressName;
    @BindView(R.id.tv_address_phone)
    TextView tvAddressPhone;
    @BindView(R.id.tv_address_detail)
    TextView tvAddressDetail;
    @BindView(R.id.ll_address_info)
    ConstraintLayout llAddressInfo;
    @BindView(R.id.tv_coupon)
    TextView tvCoupon;
    @BindView(R.id.ll_coupon)
    LinearLayout llCoupon;
    @BindView(R.id.tv_money_total)
    TextView tvMoneyTotal;
    @BindView(R.id.txt_confirm)
    TextView txtConfirm;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.ll_shop_title)
    LinearLayout llShopTitle;
    @BindView(R.id.iv_good_pic)
    ImageView ivGoodPic;
    @BindView(R.id.iv_self_support)
    ImageView ivSelfSupport;
    @BindView(R.id.tv_good_name)
    TextView tvGoodName;
    @BindView(R.id.tv_vip_price)
    TextView tvVipPrice;
    @BindView(R.id.tv_normal_price)
    TextView tvNormalPrice;
    @BindView(R.id.good_amount)
    ShoppingcartAmountView goodAmount;
    @BindView(R.id.tv_postage)
    TextView tvPostage;
    @BindView(R.id.ll_item_pay_detail)
    LinearLayout llItemPayDetail;
    @BindView(R.id.ll_complete_address)
    LinearLayout llCompleteAddress;
    @BindView(R.id.fl_address)
    FrameLayout flAddress;
    @BindView(R.id.tv_complete_address)
    TextView tvCompleteAddress;
    @BindView(R.id.ll_alipay)
    LinearLayout llAlipay;
    @BindView(R.id.ll_wechat)
    LinearLayout llWechat;
    @BindView(R.id.ll_paypal)
    LinearLayout llPaypal;
    private String token;

    private String good_id;
    private String store_id;
    private String goods_num;
    //购物车id用,隔开
    private String shopping_id;
    //1:上门取货 2:快递发货
    private String deliver = "1";
    //商品id 用,隔开
    private StringBuilder p_id = new StringBuilder();
    //门店id多商品门店id,隔开
    private StringBuilder s_id = new StringBuilder();
    //商品数量用,隔开
    private StringBuilder p_num = new StringBuilder();
    //商品总金额
    private double totalPrice;
    //地址id,如果选择上门取货则为null
    private String address_id = "";
    //优惠券id
    private String coupon_id = "";
    //1:包邮;2到付 用,拼接
    private StringBuilder freight = new StringBuilder();
    //支付方式 1:微信;2:支付宝;3:网银;4:余额
    private String payment = "2";
    private List<PayDetailShoppingBean> list;
    private PayDetailAdapter payDetailAdapter;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    private static final int REQUEST_ADDRESS = 0x0001;
    private static final int REQUEST_COUPON = 0x0002;
    private String aroundShopId;
    private List<PayDetailShoppingBean> shoppingCartList;

    public static Intent createIntent(Context context, String good_id, String store_id, String shopping_id, String goods_num) {
        Intent intent = new Intent(context, PayDetailActivity.class);
        intent.putExtra("good_id", good_id);
        intent.putExtra("store_id", store_id);
        intent.putExtra("shopping_id", shopping_id);
        intent.putExtra("goods_num", goods_num);
        return intent;
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_paydetail);
        EventBus.getDefault().register(this);
        token = SharedPreferencesUtil.getsInstances(this).getLoginInfo().getToken();
        Intent intent = getIntent();
        good_id = intent.getStringExtra("good_id");
        store_id = intent.getStringExtra("store_id");
        shopping_id = intent.getStringExtra("shopping_id");
        goods_num = intent.getStringExtra("goods_num");
    }

    @Override
    protected void initPresenter() {
        mPresenter = new PayDetailPresenter(this);
    }

    @Override
    protected void init() {
        cbAlipay.setChecked(true);
        setTopView();

        cbHome.setChecked(true);
        mPresenter.getAddressList(token);
        //6.0以上权限获取
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) permissionCheck();

        //从两个界面跳转返回数据格式不同,针对做不同布局
        if (good_id != null) {
            llItemPayDetail.setVisibility(View.VISIBLE);
            recyclerview.setVisibility(View.GONE);
            mPresenter.getGoodsInfoFromGoodDetail(token, good_id, store_id);
        } else {
            llItemPayDetail.setVisibility(View.GONE);
            recyclerview.setVisibility(View.VISIBLE);
            recyclerview.setLayoutManager(new FullyLinearLayoutManager(this));
            recyclerview.setNestedScrollingEnabled(false);
            list = new ArrayList<>();
            payDetailAdapter = new PayDetailAdapter(this, R.layout.item_pay_detail_shopping_cart, list);
            recyclerview.setAdapter(payDetailAdapter);
            payDetailAdapter.setOnMoneyChangeListener(() -> {
                p_num = new StringBuilder();
                List<PayDetailShoppingBean> data = payDetailAdapter.getDatas();
                for (int i = 0; i < data.size(); i++) {
                    PayDetailShoppingBean bean = data.get(i);
                    List<PayDetailShoppingBean.ListBean> list = bean.getList();
                    for (int j = 0; j < list.size(); j++) {
                        PayDetailShoppingBean.ListBean listBean = list.get(j);
                        if (i == data.size() - 1 && j == list.size() - 1) {
                            p_num.append(listBean.getO_num());
                        } else {
                            p_num.append(listBean.getO_num()).append(",");
                        }
                    }
                }
                tvMoneyTotal.setText("正在计算中");
                mPresenter.caculatePrice(token, p_id.toString(), p_num.toString(), coupon_id);
            });
            mPresenter.getGoodsInfoFromShoppingCart(token, shopping_id, goods_num);
        }

        //上门取货
        cbHome.setOnToggleClickListener(isChecked -> {
            if (isChecked) {
                deliver = "1";
                txtAddress.setVisibility(View.VISIBLE);
                flAddress.setVisibility(View.GONE);
                cbExpress.setChecked(false);
                s_id = new StringBuilder();
                if (good_id != null) {
                    s_id.append(aroundShopId);
                } else {
                    for (int i = 0; i < shoppingCartList.size(); i++) {
                        if (i != shoppingCartList.size() - 1) {
                            s_id.append(aroundShopId).append(",");
                        } else {
                            s_id.append(aroundShopId);
                        }
                    }
                }
            }
        });

        //快递送货
        cbExpress.setOnToggleClickListener(isChecked -> {
            if (isChecked) {
                deliver = "2";
                txtAddress.setVisibility(View.GONE);
                flAddress.setVisibility(View.VISIBLE);
                cbHome.setChecked(false);
                s_id = new StringBuilder();
                if (good_id != null) {
                    s_id.append(store_id);
                } else {
                    for (int i = 0; i < shoppingCartList.size(); i++) {
                        PayDetailShoppingBean bean = shoppingCartList.get(i);
                        if (i != shoppingCartList.size() - 1) {
                            s_id.append(bean.getC_id()).append(",");
                        } else {
                            s_id.append(bean.getC_id());
                        }
                    }
                }
            }
        });

        //支付宝
        cbAlipay.setOnToggleClickListener(isChecked -> {
            if (isChecked) {
                payment = "2";
                cbWechat.setChecked(false);
                cbBank.setChecked(false);
            }
        });
        //微信
        cbWechat.setOnToggleClickListener(isChecked -> {
            if (isChecked) {
                payment = "1";
                cbAlipay.setChecked(false);
                cbBank.setChecked(false);
            }
        });
        //银联
        cbBank.setOnToggleClickListener(isChecked -> {
            if (isChecked) {
                payment = "3";
                cbWechat.setChecked(false);
                cbAlipay.setChecked(false);
            }
        });
    }

    private void permissionCheck() {
        PermissionGen.with(this)
                .addRequestCode(100)
                .permissions(
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .request();
    }

    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    private void setTopView() {
        imgLeft.setImageResource(R.mipmap.icon_close_black);
        txtTitle.setText("立即下单");
    }

    @OnClick({R.id.ll_leftview, R.id.txt_confirm, R.id.tv_complete_address, R.id.ll_address_info,
            R.id.ll_coupon, R.id.ll_alipay, R.id.ll_wechat, R.id.ll_paypal})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_leftview:
                finish();
                break;
            case R.id.txt_confirm:
                mPresenter.getOrderNumber(token, deliver, s_id.toString(), String.valueOf(totalPrice), p_id.toString(),
                        p_num.toString(), address_id, coupon_id, freight.toString(), payment);
                break;
            case R.id.tv_complete_address:
            case R.id.ll_address_info:
                startActivityForResult(AddressActivity.createIntent(this, "pay"), REQUEST_ADDRESS);
                break;
            case R.id.ll_coupon:
                startActivityForResult(CouponActivity.createIntent(this, "good", p_id.toString()), REQUEST_COUPON);
                break;
            case R.id.ll_alipay:
                if (!cbAlipay.isChecked()) {
                    payment = "2";
                    cbAlipay.setChecked(true);
                    cbWechat.setChecked(false);
                    cbBank.setChecked(false);
                }
                break;
            case R.id.ll_wechat:
                if (!cbWechat.isChecked()) {
                    payment = "1";
                    cbAlipay.setChecked(false);
                    cbWechat.setChecked(true);
                    cbBank.setChecked(false);
                }
                break;
            case R.id.ll_paypal:
                if (!cbBank.isChecked()) {
                    payment = "3";
                    cbAlipay.setChecked(false);
                    cbWechat.setChecked(false);
                    cbBank.setChecked(true);
                }
                break;
        }
    }

    @PermissionFail(requestCode = 100)
    public void doFailSomething() {
        ToastUtils.showToast("定位失败,无法上门取货");
        deliver = "2";
        cbHome.setChecked(false);
        cbExpress.setChecked(true);
        llHome.setVisibility(View.GONE);
        flAddress.setVisibility(View.VISIBLE);
    }

    @PermissionSuccess(requestCode = 100)
    public void success() {
        initLocation();
    }

    @Override
    public void setPayDetailShoppingCart(List<PayDetailShoppingBean> data) {
        shoppingCartList = data;
        payDetailAdapter.setDatas(data);
        for (int i = 0; i < data.size(); i++) {
            PayDetailShoppingBean bean = data.get(i);
            List<PayDetailShoppingBean.ListBean> list = bean.getList();
            for (int j = 0; j < list.size(); j++) {
                PayDetailShoppingBean.ListBean listBean = list.get(j);
                if (i == data.size() - 1 && j == list.size() - 1) {
                    p_id.append(listBean.getB_id());
                    s_id.append(bean.getC_id());
                    p_num.append(listBean.getO_num());
                    freight.append(listBean.getShipping());
                } else {
                    p_id.append(listBean.getB_id()).append(",");
                    s_id.append(bean.getC_id()).append(",");
                    p_num.append(listBean.getO_num()).append(",");
                    freight.append(listBean.getShipping()).append(",");
                }
            }
        }
        tvMoneyTotal.setText("正在计算中");
        mPresenter.caculatePrice(token, p_id.toString(), p_num.toString(), coupon_id);
    }

    @Override
    public void setHomeDeliver(HomeDeliverBean data) {
        aroundShopId = data.getId();
        s_id = new StringBuilder();
        if (good_id != null) {
            s_id.append(aroundShopId);
        } else {
            for (int i = 0; i < shoppingCartList.size(); i++) {
                if (i != shoppingCartList.size() - 1) {
                    s_id.append(aroundShopId).append(",");
                } else {
                    s_id.append(aroundShopId);
                }
            }
        }
        txtAddress.setText(data.getName() + " " + data.getProvince() + data.getCity() + data.getArea() + data.getAddresser());
    }

    @Override
    public void setPayDetailGoods(PayDetailBean data) {
        totalPrice += Double.parseDouble(data.getPrice_vip());
        tvMoneyTotal.setText(String.format(ResourcesUtils.getString(R.string.good_price),
                new DecimalFormat("0.00").format(totalPrice)));
        p_id.append(good_id);
        s_id.append(store_id);
        p_num.append("1");
        tvShopName.setText(data.getC_name() != null ? data.getC_name() : "总店");
        GlideImgManager.glideLoader(mContext, RetrofitSource.image_url + data.getPic().split(",")[0], R.mipmap.img_error, R.mipmap.img_error, ivGoodPic);
        tvGoodName.setText(data.getName());
        ivSelfSupport.setVisibility(data.getSelf_support().equals("y") ? View.VISIBLE : View.GONE);
        tvVipPrice.setText(String.format(ResourcesUtils.getString(R.string.vip_good_price), data.getPrice_vip()));
        tvNormalPrice.setText(String.format(ResourcesUtils.getString(R.string.normal_good_price), data.getPrice()));
        goodAmount.setOnBtnClickListener(new ShoppingcartAmountView.BtnClickListener() {
            @Override
            public void onBtnClickPlus(View view, int amount) {
                goodAmount.setNum(++amount);
                p_num = new StringBuilder();
                p_num.append(String.valueOf(amount));
                tvMoneyTotal.setText("正在计算中");
                mPresenter.caculatePrice(token, good_id, String.valueOf(amount), coupon_id);
            }

            @Override
            public void onBtnClickDecrease(View view, int amount) {
                goodAmount.setNum(--amount);
                p_num = new StringBuilder();
                p_num.append(String.valueOf(amount));
                tvMoneyTotal.setText("正在计算中");
                mPresenter.caculatePrice(token, good_id, String.valueOf(amount), coupon_id);
            }
        });
        tvPostage.setText(data.getShipping().equals("1") ? "包邮" : "到付");
        freight.append(data.getShipping().equals("1") ? "1" : "2");
    }

    @Override
    public void setAddressInfo(List<AddressItemBean> data) {
        if (data.size() > 0) {
            llAddressInfo.setVisibility(View.VISIBLE);
            llCompleteAddress.setVisibility(View.GONE);
            for (AddressItemBean bean : data) {
                if (bean.getDefaults().equals("1")) {
                    setAddressInfo(bean);
                    return;
                }
            }
            setAddressInfo(data.get(0));
        } else {
            llAddressInfo.setVisibility(View.GONE);
            llCompleteAddress.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void setPrice(PriceBean data) {
        String money = data.getMoney();
        totalPrice = Double.parseDouble(money);
        tvMoneyTotal.setText(String.format(ResourcesUtils.getString(R.string.good_price),
                money));
    }

    @Override
    public void aliPay(String order_num) {
        new Alipay(this, order_num, new Alipay.AlipayResultCallBack() {
            @Override
            public void onSuccess() {
                startActivity(AppointmentSuccessActivity.createIntent(PayDetailActivity.this, null));
            }

            @Override
            public void onDealing() {
                ToastUtils.showToast("支付处理中...");
            }

            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case Alipay.ERROR_RESULT:
                        ToastUtils.showToast("支付失败:支付结果解析错误");
                        break;

                    case Alipay.ERROR_NETWORK:
                        ToastUtils.showToast("支付失败:网络连接错误");
                        break;

                    case Alipay.ERROR_PAY:
                        ToastUtils.showToast("支付错误:支付码支付失败");
                        break;

                    default:
                        ToastUtils.showToast("支付错误");
                        break;
                }
            }

            @Override
            public void onCancel() {
                ToastUtils.showToast("支付取消");
            }
        }).doPay();
    }

    @Override
    public void wxPay(WXPayBean data) {
        doWXPay(data);
    }

    //微信支付
    private void doWXPay(WXPayBean pay_param) {
        WXPayUtils.WXPayBuilder builder = new WXPayUtils.WXPayBuilder();
        builder.setAppId(pay_param.getAppid())
                .setPartnerId(pay_param.getPartnerid())
                .setPrepayId(pay_param.getPrepayid())
                .setPackageValue(pay_param.getPackageX())
                .setNonceStr(pay_param.getNoncestr())
                .setTimeStamp(pay_param.getTimestamp())
                .setSign(pay_param.getSign())
                .build().toWXPayNotSign(this, pay_param.getAppid());
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void getWxPayCode(MessageEvent event) {
        if (event.getMessage().equals("pay_success")) {
            finish();
        }
        if (event.getFrom() != null && event.getFrom().equals("wechat")) {
            String message = event.getMessage();
            switch (message) {
                case "0":
                    ToastUtils.showToast("支付成功");
                    startActivity(AppointmentSuccessActivity.createIntent(this, null));
                    break;
                case "-1":
                    ToastUtils.showToast("支付失败");
                    break;
                case "-2":
                    ToastUtils.showToast("用户取消");
                    break;
            }
        }
    }

    private void setAddressInfo(AddressItemBean bean) {
        llCompleteAddress.setVisibility(View.GONE);
        llAddressInfo.setVisibility(View.VISIBLE);
        tvAddressName.setText(bean.getShop_name());
        tvAddressPhone.setText(bean.getPhone());
        tvAddressDetail.setText(bean.getProvince() + bean.getCity() + bean.getArea() + bean.getAddress());
        address_id = bean.getId();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        double latitude = aMapLocation.getLatitude();
        double longitude = aMapLocation.getLongitude();
        mPresenter.getHomeDeliver(null, latitude, longitude);
        Log.i(TAG, "onLocationChanged:" + latitude + "," + longitude);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (requestCode) {
                case REQUEST_ADDRESS:
                    AddressItemBean addressBean = (AddressItemBean) data.getSerializableExtra("addressBean");
                    setAddressInfo(addressBean);
                    break;
                case REQUEST_COUPON:
                    tvCoupon.setText(data.getStringExtra("couponName"));
                    coupon_id = data.getStringExtra("couponId");
                    tvMoneyTotal.setText("正在计算中");
                    mPresenter.caculatePrice(token, p_id.toString(), p_num.toString(), coupon_id);
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

}
